<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <el-form ref="form" :model="formData" label-width="120px">
          <el-row>
            <el-col :span="14">
              <el-form-item label="药品名称" prop="drugName">
                <el-input v-model="formData.drugName" />
              </el-form-item>
            </el-col>
            <el-col v-show="formData.drugName.length !== 0" :span="10">
              <el-form-item label="药品规格" prop="specification">
                <el-input v-model="formData.specification" type="number" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="按患者姓名筛选" prop="patientName">
            <el-select v-model="formData.patientName" filterable placeholder="请选择" @focus="fetchPatientNameData">
              <el-option
                v-for="item in patientNameDDList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分类" prop="drugClassification">
            <el-select v-model="formData.drugClassification" multiple filterable placeholder="请选择" @focus="fetchDrugClassificationData">
              <el-option
                v-for="item in drugClassificationDDList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="医院名称" prop="hospital">
            <el-select v-model="formData.hospital" multiple filterable placeholder="请选择" @focus="fetchHospitalData">
              <el-option
                v-for="item in hospitalDDList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间区间">
            <el-date-picker
              v-model="dateTimePickerVal"
              autocomplete="off"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              align="right"
              value-format="timestamp"
              format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <!--  mg 开关-->
              <el-form-item label="统计毫克" prop="mg">
                <el-switch v-model="mgInputShow" @change="mgSwitchChange()" />
              </el-form-item>
              <el-form-item v-show="mgInputShow" label="单位大于（毫克）" label-width="auto" prop="mg">
                <el-input v-model="formData.mg" type="number" style="width: 30%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!--  ml 开关-->
              <el-form-item label="统计毫升" prop="ml">
                <el-switch v-model="mlInputShow" @change="mlSwitchChange()" />
              </el-form-item>
              <el-form-item v-show="mlInputShow" label="单位大于（毫升）" label-width="auto" prop="ml">
                <el-input v-model="formData.ml" type="number" style="width: 30%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <!-- 频率数字输入-->
              <el-form-item label="频率大于" prop="cnt">
                <el-input v-model.number="formData.cnt" type="number" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 跨医院数字输入-->
              <el-form-item label="跨医院大于" prop="hospitalCnt">
                <el-input v-model.number="formData.hospitalCnt" type="number" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row class="button-row">
      <el-button type="warning" :loading="listLoading" @click="summarize">立即汇总</el-button>
      <el-button type="primary" :loading="isDownloadLoading" @click="handleDownload">下载数据</el-button>
      <el-button type="danger" @click="resetForm">重置</el-button>
    </el-row>
    <div>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        stripe
        empty-text="点击立即汇总查看数据"
      >
        <el-table-column
          type="index"
          width="50px"
        />
        <el-table-column label="患者姓名" align="center" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.patientName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center">
          <template slot-scope="scope">
            {{ scope.row.age }}
          </template>
        </el-table-column>
        <el-table-column label="药品信息" align="center" min-width="90px">
          <template slot-scope="scope">
            <el-tag v-for="(drug, index) in scope.row.drugs" :key="index" style="margin-bottom: 1em">
              {{ drug }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最早时间" align="center" min-width="180">
          <template slot-scope="scope">
            {{ scope.row.earliestTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="最晚时间" align="center" min-width="180">
          <template slot-scope="scope">
            {{ scope.row.recentTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="间隔天数" align="center">
          <template slot-scope="scope">
            {{ scope.row.diffDay }}
          </template>
        </el-table-column>
        <el-table-column label="跨医院数" align="center">
          <template slot-scope="scope">
            {{ scope.row.hospitalCnt }}
          </template>
        </el-table-column>
        <el-table-column label="间隔/频率" align="center" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.t != null ? '1/'+scope.row.t : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="重复值" align="center">
          <template slot-scope="scope">
            {{ scope.row.cnt }}
          </template>
        </el-table-column>
        <el-table-column label="电话号码" align="center" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.telephoneNumber }}
          </template>
        </el-table-column>
        <el-table-column label="身份证号" align="center" min-width="180">
          <template slot-scope="scope">
            {{ scope.row.idNumber }}
          </template>
        </el-table-column>
        <el-table-column label="剂量" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.measurementUnit === 'mg' ? 'success' : 'warning' ">
              {{ scope.row.ml == null ? scope.row.mg : scope.row.ml }} {{ scope.row.measurementUnit }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" min-width="80">
          <template v-slot:default="scope">
            <el-button type="primary" plain size="small" @click="handleViewDetails(scope.row.idNumber)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        :current-page="page"
        :page-sizes="pageSizes"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- Download Dialog -->
    <el-dialog
      title="下载确认"
      :visible.sync="downloadDialogVisible"
      width="30%"
      @close="downloadDialogVisible = false"
    >
      <p>是否按照当前搜索条件下载所有数据？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="downloadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDownload">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import * as summarizeAPI from '@/api/summarize'
import * as commonAPI from '@/api/common'
import '@/styles/table.scss'

export default {
  filters: {
    formatDate(value) {
      if (!value) return ''
      const date = new Date(value)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  },
  data() {
    return {
      // 控制下载确认对话框的显示和隐藏
      downloadDialogVisible: false,
      list: null,
      listLoading: false,
      dateTimePickerVal: [],
      formData: {
        'patientName': '',
        'prescriptionStartTime': '',
        'prescriptionEndTime': '',
        'cnt': '0',
        'drugName': '',
        'specification': '0',
        'drugClassification': [],
        'hospital': [],
        'hospitalCnt': '0',
        'mg': '-1',
        'ml': '-1'
      },
      size: 10,
      page: 1,
      total: 0,
      pageSizes: [10, 25, 50, 100],
      // 下拉菜单值
      // drugNameDDList: [], 废弃 下一版本删除
      drugClassificationDDList: [],
      hospitalDDList: [],
      patientNameDDList: [],
      // mg 和 ml 输入框显示
      mgInputShow: false,
      mlInputShow: false,
      isDownloadLoading: false
    }
  },
  watch: {
    // 限制 cnt 字段的输入，至少是 0
    'formData.cnt'(newVal) {
      if (newVal === '') {
        this.formData.cnt = '0'
      }
    }
  },
  created() {
    // this.fetchData()
  },
  mounted() {
    // 从路由守卫恢复保存在 localStorage 中的数据
    this.list = JSON.parse(localStorage.getItem('list')) || []
    this.total = parseInt(localStorage.getItem('total')) || 0
    this.page = parseInt(localStorage.getItem('page')) || 1
    this.size = parseInt(localStorage.getItem('size')) || 10
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const pageObj = {
        page: this.page,
        size: this.size
      }
      summarizeAPI.summaryList(pageObj, this.formData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    summarize() {
      this.listLoading = true
      const pageObj = {
        page: this.page,
        size: this.size
      }
      // 封装时间区间，增加 if 判断的作用是避免因为 picker 在 clear 后，其绑定的 val 返回 null 导致的报错
      if (this.dateTimePickerVal) {
        this.formData.prescriptionStartTime = this.dateTimePickerVal[0]
        this.formData.prescriptionEndTime = this.dateTimePickerVal[1]
      } else {
        this.formData.prescriptionStartTime = '' // 或者你的默认值
        this.formData.prescriptionEndTime = '' // 或者你的默认值
      }
      // 调用 summarizeList API
      summarizeAPI.summaryList(pageObj, this.formData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields()
      this.dateTimePickerVal = []
      this.mgInputShow = false
      this.mlInputShow = false
    },
    // 分页：页码改变
    handleSizeChange(val) {
      this.size = val
      this.summarize()
    },
    // 分页：每页显示数量改变
    handleCurrentChange(val) {
      this.page = val
      this.summarize()
    },
    // 按钮点击事件：一键下载数据，按照当前搜索条件下载
    handleDownload() {
      // 显示下载确认对话框
      this.downloadDialogVisible = true
    },
    // 按钮点击事件：确认下载
    confirmDownload() {
      this.isDownloadLoading = true
      this.$message({
        message: '正在开始下载，请勿刷新或关闭页面',
        type: 'info',
        duration: 0
      })

      // 调用 downloadByCondition 方法
      summarizeAPI.summaryDownload(this.formData)
        .then(response => {
          // 将文件内容转换为 Blob
          const blob = response.data

          // 创建一个 Blob URL
          const url = window.URL.createObjectURL(blob)

          // 创建一个链接，并将其 href 属性设置为 Blob URL
          const link = document.createElement('a')
          link.href = url

          // 设置下载的文件名
          link.download = `summarized.xlsx`

          // 将链接添加到文档中
          document.body.appendChild(link)

          // 模拟点击链接
          link.click()

          // 移除链接
          document.body.removeChild(link)
          // 关闭加载动画和消息提示
          this.isDownloadLoading = false
          this.$message.closeAll()
        })
        .catch(error => {
          // 处理错误
          console.error(error)
          this.isDownloadLoading = false
          this.$message.closeAll()
        })

      // 关闭下载确认对话框
      this.downloadDialogVisible = false
    },
    handleViewDetails(idNumber) {
      this.$router.push({
        name: 'Details',
        params: {
          idNumber: idNumber,
          page: this.page,
          size: this.size,
          formData: this.formData
        }
      })
    },

    // 废弃，下一个版本删除
    // 下拉框焦点事件：获取药品名称数据的方法
    // fetchDrugNameData() {
    //   // 如果药品名称数据已经被加载过（即 drugNameDDList 数组的长度大于 0），那么就不再请求接口
    //   if (this.drugNameDDList.length > 0) {
    //     return
    //   }
    //   commonAPI.getDrugNameList()
    //     .then(response => {
    //       if (response.code === 200) {
    //         this.drugNameDDList = response.data.list
    //       } else {
    //         console.error(response.msg)
    //       }
    //     })
    //     .catch(error => {
    //       console.error(error)
    //     })
    // },
    // 下拉框焦点事件：获取药品分类数据的方法
    fetchDrugClassificationData() {
      if (this.drugClassificationDDList.length > 0) {
        return
      }
      commonAPI.getDrugClassificationList()
        .then(response => {
          if (response.code === 200) {
            this.drugClassificationDDList = response.data.list
          } else {
            console.error(response.msg)
          }
        })
        .catch(error => {
          console.error(error)
        })
    },

    // 下拉框焦点事件：获取医院数据的方法
    fetchHospitalData() {
      if (this.hospitalDDList.length > 0) {
        return
      }
      commonAPI.getHospitalList()
        .then(response => {
          if (response.code === 200) {
            this.hospitalDDList = response.data.list
          } else {
            console.error(response.msg)
          }
        })
        .catch(error => {
          console.error(error)
        })
    },
    // 获取患者姓名数据
    fetchPatientNameData() {
      if (this.patientNameDDList.length > 0) {
        return
      }
      commonAPI.getPatientNameList()
        .then(response => {
          if (response.code === 200) {
            this.patientNameDDList = response.data.list
          } else {
            console.error(response.msg)
          }
        })
        .catch(error => {
          console.error(error)
        })
    },
    mgSwitchChange() {
      if (this.mgInputShow === false) {
        this.formData.mg = -1
      } else {
        this.formData.mg = 0
      }
    },
    mlSwitchChange() {
      if (this.mlInputShow === false) {
        this.formData.ml = -1
      } else {
        this.formData.ml = 0
      }
    },
    // 格式化：2023-12-23T04:02:13.000+00:00 风格的时间
    formatTime(dateString) {
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  },
  // 导航离开该组件的对应路由时调用，
  beforeRouteLeave(to, from, next) {
    // 将数据保存到localStorage
    localStorage.setItem('list', JSON.stringify(this.list))
    localStorage.setItem('total', this.total)
    localStorage.setItem('page', this.page)
    localStorage.setItem('size', this.size)
    // 继续导航
    next()
  }
}
</script>
